package com.baidu.videoseries.service;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.view.View;

import com.baidu.videoseries.MainActivity;
import com.baidu.videoseries.R;
import com.baidu.videoseries.bean.MediaBean;
import com.baidu.videoseries.constant.Config;
import com.baidu.videoseries.receiver.MusicReceiver;
import com.baidu.videoseries.util.LogUtils;
import com.kvin.toolkit.utils.FileUtils;
import com.kvin.toolkit.utils.StringUtils;

import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;

import java.util.ArrayList;

public class AudioService extends Service {

    private LibVLC mLibVLC;
    private MediaPlayer mMediaPlayer;
    private Media mMedia;

    public static final int NOTIFICATION_ID = 111;

    private ArrayList<MediaBean> mData;
    private int cursorIndex;
    private String mTitle;
    private MusicReceiver musicReceiver;
    private NotificationManager mManager;

    public AudioService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            musicReceiver = new MusicReceiver();
            registerReceiver(musicReceiver, new IntentFilter(Config.MediaAction.ACTION_COMMAND));
            musicReceiver.setOnReceiveListener(new ReceiverListener());
            mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //init player here
            ArrayList<String> args = new ArrayList<>();
            args.add("-vvv");
//            args.add("-atmo-channels=4");

            mLibVLC = new LibVLC(this,args);
            mMediaPlayer = new MediaPlayer(mLibVLC);
            mMediaPlayer.setEventListener(new PlayerCk());
            initPlayList(intent);
            initPlayer();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * init play list
     *
     * @param intent
     */
    private void initPlayList(Intent intent) {
        if (mData == null)
            this.mData = new ArrayList<>();
        if (mData.size() > 0) mData.clear();
        this.cursorIndex = intent.getIntExtra(Config.Key.CURSOR_INDEX, -1);
        this.cursorIndex = cursorIndex == -1 ? 0 : cursorIndex;
        MediaBean bean = intent.getParcelableExtra(Config.Key.FILE);
        if (bean != null) mData.add(bean);
        ArrayList<MediaBean> temp = intent.getParcelableArrayListExtra(Config.Key.FILE_LIST);
        if (temp != null) mData.addAll(temp);
    }

    /**
     * add file and set listener
     */
    private void initPlayer() {
        if (mData == null || mData.size() < 1 || cursorIndex >= mData.size()) return;
        if (mMediaPlayer.isPlaying()) mMediaPlayer.pause();
        if (mMedia != null) mMedia.release();
        String url = mData.get(cursorIndex).getTargetUrl();
        mTitle = mData.get(cursorIndex).getStoryName();
        Uri uri = url.startsWith("http") ? Uri.parse(url) : Uri.fromFile(FileUtils.newFile(url));
        mMedia = new Media(mLibVLC, uri);
        mMediaPlayer.setMedia(mMedia);
        mMedia.parseAsync();
        mMediaPlayer.setTitle(1);
        mMediaPlayer.setSpuDelay(2 * 1000);
        mMediaPlayer.play();
    }


    /**
     * player ck
     */
    class PlayerCk implements MediaPlayer.EventListener {
        @Override
        public void onEvent(MediaPlayer.Event event) {
            switch (event.type) {
                case MediaPlayer.Event.Opening:
                    LogUtils.e("--" + event.type + " :length=" + mMediaPlayer.getLength());
                    break;
                case MediaPlayer.Event.Playing:
//                    loadingView.setVisibility(View.GONE);
//                    isPlaying = true;
                    break;
                case MediaPlayer.Event.Stopped:
//                    isPlaying = false;
                    break;
                case MediaPlayer.Event.TimeChanged:
                    int progress = (int) (mMediaPlayer.getTime() / 1000);
                    initPendingIntent(mTitle, mMediaPlayer);
//                    mSeekBar.setProgress(progress);
//                    LogUtils.e("time=" + mMediaPlayer.getTime());
                    break;
                case MediaPlayer.Event.Vout:
                    int length = (int) mMediaPlayer.getLength() / 1000;
//                    mSeekBar.setMax(length);
                    if (!mMediaPlayer.isPlaying()) mMediaPlayer.play();
                    LogUtils.e("Vout", " :length=" + mMediaPlayer.getLength());
                    break;
                case MediaPlayer.Event.MediaChanged:
                    mMediaPlayer.pause();
                    break;
                case MediaPlayer.Event.EndReached:
                    next();
                    break;
            }
        }
    }

    /**
     * init notification
     */
    private void initPendingIntent(String title, MediaPlayer mPlayer) {
        if (mPlayer == null) return;
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(getApplicationContext(), MainActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setTicker("didi")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(StringUtils.getString(title))
                .setAutoCancel(true)
                .setOnlyAlertOnce(true)
                .setOngoing(true)
                .setContentInfo("MusicPlayer")
                .setProgress((int) mPlayer.getLength(), (int) mPlayer.getTime(), false)
                .setContentIntent(pi);

        //custom notification
        //define content
//        RemoteViews mRemote = new RemoteViews(getPackageName(), R.layout.notification_playing);
//        View v = LayoutInflater.from(this).inflate(mRemote.getLayoutId(), null);
//        v.findViewById(R.id.previous_iv).setOnClickListener(mClick);
//        v.findViewById(R.id.play_iv).setOnClickListener(mClick);
//        v.findViewById(R.id.next_iv).setOnClickListener(mClick);
//        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
//                .setSmallIcon(R.mipmap.ic_launcher,10)
//                .setContent(mRemote);
//                .setContentIntent(pi);

        mManager.notify(NOTIFICATION_ID, builder.build());
    }


    /**
     * on receiver listener
     */
    class ReceiverListener implements MusicReceiver.OnReceiverListener {
        @Override
        public void onReceive(Context context, Intent intent) {
            int command = intent.getIntExtra(Config.Key.COMMAND, -1);
            if (command == Config.Command.PLAY) {
                if (!mMediaPlayer.isPlaying()) mMediaPlayer.play();
                return;
            }
            if (command == Config.Command.PAUSE) {
                if (mMediaPlayer.isPlaying()) mMediaPlayer.pause();
                return;
            }
            if (command == Config.Command.PREVIOUS) {
                previous();
                return;
            }
            if (command == Config.Command.NEXT) {
                next();
                return;
            }
            if (command == Config.Command.CURSOR_INDEX) {
                int index = intent.getIntExtra(Config.Key.CURSOR_INDEX, -1);
                if (index == cursorIndex) return;
                cursorIndex = (index == -1) ? cursorIndex : index;
                initPlayer();
            }
        }
    }

    private void previous() {
        cursorIndex--;
        if (cursorIndex < 0) cursorIndex = mData.size() - 1;
        cursorIndex = cursorIndex >= 0 ? cursorIndex : 0;
        initPlayer();
    }

    /**
     * on click listener
     */
    private View.OnClickListener mClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.previous_iv) {
                previous();
                return;
            }
            if (v.getId() == R.id.next_iv) {
                next();
                return;
            }
        }
    };


    private void next() {
        cursorIndex++;
        if (cursorIndex >= mData.size()) cursorIndex = 0;
        initPlayer();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mLibVLC.release();
            mMedia.release();
        }

        unregisterReceiver(musicReceiver);
    }
}
